package com.noble.glamour.third.auth;

import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.widget.Toast;

import com.noble.glamour.module.logic.application.App;
import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.util.TimerUtil;
import com.noble.library.third.ThirdConstant;
import com.noble.library.observe.ModuleBase;
import com.noble.library.third.auth.OauthCallback;
import com.noble.library.third.auth.ThirdInfo;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONObject;

/**
 * 三方授权类
 * Created by Kind on 2016/12/14.
 */

public class AuthMgr implements ModuleBase {
    private FragmentActivity mActivity = (FragmentActivity) App.getActivity();
    private OauthCallback mCallback;

    @Override
    public void init() {
        initQQ();  // QQ授权
        initWX();  // WX授权
    }

    @Override
    public void release() {
        mCallback = null;
        onQQLoginOut();
    }

    // ================================= 外部暴露方法 =================================================

    /**
     * 三方登录选择
     *
     * @param loginType 登录方式
     */
    public void onLogin(int loginType) {
        switch (loginType) {
            case ThirdConstant.QQ:
                onQQ();
                break;

            case ThirdConstant.WECHAT:
                onWechat();
                break;
        }
    }

    public void setCallback(OauthCallback callback) {
        this.mCallback = callback;
    }

    public OauthCallback getCallback() {
        return mCallback;
    }

    /**
     * @return 获取微信接口对象
     */
    public IWXAPI getWXApi() {
        return mApi;
    }

    // ================================= 内部授权调用 =================================================
    // --------------------------微信授权  start--------------------------------
    private IWXAPI mApi;

    /**
     * 微信SDK通信接口初始化
     */
    private void initWX() {
        mApi = WXAPIFactory.createWXAPI(mActivity, ThirdConstant.WEIXIN_APP_ID, true); // boolean参数标记是否检测微信客户端的签名是否正确
    }

    /**
     * 微信授权登陆
     */
    private void onWechat() {
        ThirdConstant.mPlatform = ThirdConstant.WECHAT;
        if (!mApi.isWXAppInstalled()) {
            Toast.makeText(mActivity, "您还没有安装微信！", Toast.LENGTH_SHORT).show();
            return;
        }

        mApi.registerApp(ThirdConstant.WEIXIN_APP_ID);
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = ThirdConstant.WECHAT_SCOPE;
        req.state = ThirdConstant.WECHAT_STATE; // 非必须
        mApi.sendReq(req);
    }
    // --------------------------微信授权 end--------------------------------


    // --------------------------QQ授权 start--------------------------------
    private Tencent mTencent;
    private String openId;

    /**
     * Tencent SDK的功能入口初始化
     */
    private void initQQ() {
        mTencent = Tencent.createInstance(ThirdConstant.QQ_APP_ID, App.getActivity().getApplicationContext());
    }

    /**
     * QQ授权登录
     */
    private void onQQ() {
        ThirdConstant.mPlatform = ThirdConstant.QQ;
        mActivity = (FragmentActivity) App.getActivity();
        TimerUtil.beginTime(new TimerUtil.CallBack() {
            @Override
            public void call() {
                if (!mTencent.isSessionValid()) {
                    mTencent.login(mActivity, ThirdConstant.QQ_SCOPE, new QQOauthCallback(QQOauthCallback.TYPE_OAUTH));
                }
            }
        }, 300);
    }

    /**
     * QQ取消授权
     */
    private void onQQLoginOut() {
        mTencent.logout(mActivity);
    }

    /**
     * 保证Tencent成功接收回调
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (ThirdConstant.mPlatform == ThirdConstant.QQ) {
            Tencent.onActivityResultData(requestCode, resultCode, data, null);
        }
    }

    /**
     * Tencent 回调接口实现
     */
    class QQOauthCallback implements IUiListener {
        static final int TYPE_OAUTH = 1;
        static final int TYPE_INFO = 2;

        private final int type;

        public QQOauthCallback(int type) {
            this.type = type;
        }

        @Override
        public void onCancel() {
            if (mCallback != null) {
                onQQLoginOut();
                mCallback.onCancelled(ThirdConstant.QQ);
            }
        }

        @Override
        public void onComplete(Object object) {
            if (mCallback != null) {
                if (object == null) {    // 未返回结果
                    if (type == TYPE_OAUTH) {
                        mCallback.onFailure(ThirdConstant.QQ, "QQ oauth return null");
                    } else {
                        mCallback.onFailure(ThirdConstant.QQ, "QQ fetch user info return null");
                    }
                } else if (object instanceof JSONObject) {  // 成功返回
                    JSONObject json = (JSONObject) object;
                    if (type == TYPE_OAUTH) {
                        String token = json.optString(Constants.PARAM_ACCESS_TOKEN);
                        String expires = json.optString(Constants.PARAM_EXPIRES_IN);
                        openId = json.optString(Constants.PARAM_OPEN_ID);
                        if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires) && !TextUtils.isEmpty(openId)) {
                            mTencent.setAccessToken(token, expires);
                            mTencent.setOpenId(openId);

                            // 用户资料获取
                            UserInfo userInfo = new UserInfo(mActivity.getApplicationContext(), mTencent.getQQToken());
                            userInfo.getUserInfo(new QQOauthCallback(TYPE_INFO));
                        }
                    } else {
                        ThirdInfo u = ThirdInfo.qq(json);
                        if (u == null) {
                            mCallback.onFailure(ThirdConstant.QQ, "fetch user info fail");
                        } else {
                            u.setOpenid(openId);
                            u.setPlat(ThirdConstant.QQ);
                            mCallback.onSuccess(ThirdConstant.QQ, u);
                        }
                        ModuleMgr.getLoginMgr().setThirdInfo(u);
                    }
                } else {  // 返回结果有误
                    if (type == TYPE_OAUTH) {
                        mCallback.onFailure(ThirdConstant.QQ, "QQ oauth return data cannot be cast to JSONObject");
                    } else {
                        mCallback.onFailure(ThirdConstant.QQ, "QQ fetch user info return data cannot be cast to JSONObject");
                    }
                }
                onQQLoginOut();
            }
        }

        @Override
        public void onError(UiError error) {
            if (mCallback != null) {
                onQQLoginOut();
                mCallback.onError(ThirdConstant.QQ, new Exception(error.errorMessage));
            }
        }
    }
    // --------------------------QQ授权 end--------------------------------
}
